
// Copyright (c) WanSheng Intelligent Corp. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.


#include "file_util.h"
#include <stdio.h>
#include <stdlib.h> // For exit()

#define MAX_PACKET_SIZE 8*1024
bool get_file_md5(char * filepath, char * hash)
{
    unsigned char c[MD5_DIGEST_LENGTH];
    int i;
    FILE *inFile = fopen (filepath, "rb");
    MD5_CTX mdContext;
    int bytes;

    unsigned char data[MAX_PACKET_SIZE];
    if (inFile == NULL)
    {
        return false;
    }

    MD5_Init (&mdContext);
    while ((bytes = fread (data, 1, MAX_PACKET_SIZE, inFile)) != 0)
    {
        MD5_Update (&mdContext, data, bytes);
    }
    MD5_Final (c,&mdContext);
    for(i=0;i<MD5_DIGEST_LENGTH;i++)
    {
        sprintf(hash+i*2,"%02x",c[i]);
    }
    hash[MD5_DIGEST_LENGTH*2-1]=0;
    fclose (inFile);
    return true;
}



bool wa_copy_file(const char * src_path, const char * dest_path, bool replace)
{
    FILE *fp1, *fp2;

    char ch;

    int pos;

    if(!replace && access(dest_path, F_OK) == 0)
        return false;

    if ((fp1 = fopen(src_path,"r")) == NULL)    
    {    
        return false;
    }

    fp2 = fopen(dest_path, "w");  
    fseek(fp1, 0L, SEEK_END); // file pointer at end of file
    pos = ftell(fp1);
    fseek(fp1, 0L, SEEK_SET); // file pointer set at start
    while (pos--)
    {
        ch = fgetc(fp1);  // copying file character by character
        fputc(ch, fp2);
    }
    fclose(fp1);
    fclose(fp2);
    return true;
}


int wa_extract_package_tar_gz(const char * package_file, const char * target_dir)
{
    //tar -xf archive.tar -C /target/directory
    char cmd[MAX_PACKET_SIZE]={0};
    if (access(package_file, R_OK) != 0)
        return -1;

    //tar.gz using tar -xf %s -C %s; zip use unzip %s -d %s
    snprintf(cmd, sizeof(cmd),"mkdir -p %s && tar -zxf %s -C %s",
            target_dir, package_file, target_dir);

    //WARNING2("extract_package_tar_gz: %s", cmd);
    return system(cmd);
}
